package com.example.gokuplayalong.service.fragments.users.receive;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.gokuplayalong.MainActivity;
import com.example.gokuplayalong.R;
import com.example.gokuplayalong.bases.beans.AppParams;
import com.example.gokuplayalong.bases.beans.Beans;
import com.example.gokuplayalong.bases.exception.ExceptionUtils;
import com.example.gokuplayalong.bases.network.NetWorkInterface;
import com.example.gokuplayalong.bases.tools.Tools;
import com.example.gokuplayalong.service.fragments.users.others.UserMainChat;
import com.example.gokuplayalong.service.fragmentsmanage.SysManagerFragments;
import com.kongzue.dialogx.dialogs.BottomMenu;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.PopTip;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.OnMenuItemClickListener;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link UserMainReceiveUserInfoPlaceOrder#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class UserMainReceiveUserInfoPlaceOrder extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    View rootView;
    JSONObject serviceType = new JSONObject();

    JSONArray skillsList = new JSONArray();

    JSONObject merchantInfo = new JSONObject();

    JSONObject data = new JSONObject();

    Beans bean = new Beans();
    private ImageView mUserMainReceiveUserinfoPlaceOrderIv;
    private ImageView mUserMainReceiveUserInfoPlaceOrderHeadshot;
    private TextView mUserMainReceiveUserInfoPlaceOrderMerchantName;
    private TextView mUserMainReceiveUserInfoPlaceOrderMerchantDesc;
    private TextView mUserMainReceiveUserInfoPlaceOrderMerchantScore;
    private TextView mUserMainReceiveUserInfoPlaceOrderMerchantGuide;
    private LinearLayout mUserMainReceiveUserInfoPlaceOrderGametype;
    private TextView mUserMainReceiveUserInfoPlaceOrderGametypeShow;
    private LinearLayout mUserMainReceiveUserInfoPlaceOrderServicetype;
    private TextView mUserMainReceiveUserInfoPlaceOrderServicetypeShow;
    private LinearLayout mUserMainReceiveUserInfoPlaceOrderStarttime;
    private TextView mUserMainReceiveUserInfoPlaceOrderStarttimeShow;
    private LinearLayout mUserMainReceiveUserInfoPlaceOrderTimes;
    private EditText mUserMainReceiveUserInfoPlaceOrderTimesInput;
    private Button mUserMainReceiveUserInfoPlaceOrderTimesInputAdd;
    private Button mUserMainReceiveUserInfoPlaceOrderTimesInputInc;
    private TextView mUserMainReceiveUserInfoPlaceOrderTimesShow;
    private Button mUserMainReceiveUserInfoPlaceOrderPlaceOrder;

    public Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1: {
                    try {
                        Bundle bundle = msg.getData();
                        bean.setJsonObject(JSON.parseObject(bundle.getString("bean")));

                    } catch (Throwable e) {
                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                    }
                }
                break;
            }
        }
    };

    public UserMainReceiveUserInfoPlaceOrder() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment UserMainReceiveUserInfoPlaceOrder.
     */
    // TODO: Rename and change types and number of parameters
    public static UserMainReceiveUserInfoPlaceOrder newInstance(String param1, String param2) {
        UserMainReceiveUserInfoPlaceOrder fragment = new UserMainReceiveUserInfoPlaceOrder();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (rootView == null)
            rootView = inflater.inflate(R.layout.fragment_user_main_receive_user_info_place_order, container, false);
        initView();
        return rootView;
    }

    private void initView() {
        mUserMainReceiveUserinfoPlaceOrderIv = rootView.findViewById(R.id.user_main_receive_userinfo_place_order_iv);
        mUserMainReceiveUserInfoPlaceOrderHeadshot = rootView.findViewById(R.id.user_main_receive_user_info_place_order_headshot);
        mUserMainReceiveUserInfoPlaceOrderMerchantName = rootView.findViewById(R.id.user_main_receive_user_info_place_order_merchant_name);
        mUserMainReceiveUserInfoPlaceOrderMerchantDesc = rootView.findViewById(R.id.user_main_receive_user_info_place_order_merchant_desc);
        mUserMainReceiveUserInfoPlaceOrderMerchantScore = rootView.findViewById(R.id.user_main_receive_user_info_place_order_merchant_score);
        mUserMainReceiveUserInfoPlaceOrderMerchantGuide = rootView.findViewById(R.id.user_main_receive_user_info_place_order_merchant_guide);
        mUserMainReceiveUserInfoPlaceOrderGametype = rootView.findViewById(R.id.user_main_receive_user_info_place_order_gametype);
        mUserMainReceiveUserInfoPlaceOrderGametypeShow = rootView.findViewById(R.id.user_main_receive_user_info_place_order_gametype_show);
        mUserMainReceiveUserInfoPlaceOrderServicetype = rootView.findViewById(R.id.user_main_receive_user_info_place_order_servicetype);
        mUserMainReceiveUserInfoPlaceOrderServicetypeShow = rootView.findViewById(R.id.user_main_receive_user_info_place_order_servicetype_show);
        mUserMainReceiveUserInfoPlaceOrderStarttime = rootView.findViewById(R.id.user_main_receive_user_info_place_order_starttime);
        mUserMainReceiveUserInfoPlaceOrderStarttimeShow = rootView.findViewById(R.id.user_main_receive_user_info_place_order_starttime_show);
        mUserMainReceiveUserInfoPlaceOrderTimes = rootView.findViewById(R.id.user_main_receive_user_info_place_order_times);
        mUserMainReceiveUserInfoPlaceOrderTimesInput = rootView.findViewById(R.id.user_main_receive_user_info_place_order_times_input);
        mUserMainReceiveUserInfoPlaceOrderTimesInputAdd = rootView.findViewById(R.id.user_main_receive_user_info_place_order_times_input_add);
        mUserMainReceiveUserInfoPlaceOrderTimesInputInc = rootView.findViewById(R.id.user_main_receive_user_info_place_order_times_input_inc);
        mUserMainReceiveUserInfoPlaceOrderPlaceOrder = rootView.findViewById(R.id.user_main_receive_user_info_place_order_place_order);


        mUserMainReceiveUserinfoPlaceOrderIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    SysManagerFragments.switchBackOnSysFragment();

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveUserInfoPlaceOrderGametype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;
                    if (skillsList == null || skillsList.isEmpty()) {
                        return;
                    }
                    String[] gameType = new String[skillsList.size()];

                    for (int i = 0; i < skillsList.size(); i++) {
                        gameType[i] = skillsList.getJSONObject(i).getString("gametype");
                    }

                    BottomMenu.show(gameType)
                            .setTitle("请选择游戏类型")
                            .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                                @Override
                                public boolean onClick(BottomMenu dialog, CharSequence text, int index) {
                                    mUserMainReceiveUserInfoPlaceOrderGametypeShow.setText(text);
                                    data.put("gameType", text);
                                    return false;
                                }
                            });
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveUserInfoPlaceOrderServicetype.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {

                    String[] serviceTypes = new String[serviceType.size()];
                    String[] serviceTypesKey = new String[serviceType.size()];
                    String[] serviceTypesValue = new String[serviceType.size()];

                    int count = 0;
                    Iterator<String> iterator = serviceType.keySet().iterator();
                    while (iterator.hasNext()) {
                        String key = iterator.next();
                        serviceTypesKey[count] = key;
                        serviceTypesValue[count] = serviceType.getString(key) + "元/小时";

                        serviceTypes[count] = key + " ";
                        serviceTypes[count] += serviceType.getString(key) + "元/小时";

                        count++;
                    }


                    BottomMenu.show(serviceTypes)
                            .setTitle("请选择服务类型")
                            .setOnMenuItemClickListener(new OnMenuItemClickListener<BottomMenu>() {
                                @Override
                                public boolean onClick(BottomMenu dialog, CharSequence text, int index) {
                                    mUserMainReceiveUserInfoPlaceOrderServicetypeShow.setText(text);
                                    data.put("serviceType", serviceTypesKey[index]);
                                    return false;
                                }
                            });
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveUserInfoPlaceOrderStarttime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    Calendar calendar = Calendar.getInstance();

                    data.put("startTimeHour", "0");
                    data.put("startTimeMinute", "0");
                    data.put("month", "1");
                    data.put("day", "1");

                    StringBuilder startTimeDateBuilder = new StringBuilder();
                    StringBuilder startTimeTimeBuilder = new StringBuilder();

                    TimePickerDialog timePickerDialog = new TimePickerDialog(rootView.getContext(), new TimePickerDialog.OnTimeSetListener() {
                        @Override
                        public void onTimeSet(TimePicker timePicker, int i, int i1) {

                            data.put("startTimeHour", String.valueOf(i));
                            data.put("startTimeMinute", String.valueOf(i1));

                            startTimeTimeBuilder.append(i).append(":").append(i1);

                            requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        mUserMainReceiveUserInfoPlaceOrderStarttimeShow.setText(String.format("%s%s", startTimeDateBuilder.toString(), startTimeTimeBuilder.toString()));

                                    } catch (Throwable e) {

                                    }
                                }
                            });
                        }
                    }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true);
                    timePickerDialog.setCanceledOnTouchOutside(false);
                    DatePickerDialog datePickerDialog = new DatePickerDialog(rootView.getContext(), new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                            data.put("month", String.valueOf(i1 + 1));
                            data.put("day", String.valueOf(i2));
                            startTimeDateBuilder.append(i1 + 1)
                                    .append("月")
                                    .append(i2)
                                    .append("日 ");
                            requireActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        mUserMainReceiveUserInfoPlaceOrderStarttimeShow.setText(String.format("%s%s", startTimeDateBuilder.toString(), startTimeTimeBuilder.toString()));

                                    } catch (Throwable e) {

                                    }
                                }
                            });
                        }
                    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                    datePickerDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialogInterface) {
                            try {
                                timePickerDialog.show();
                            } catch (Throwable e) {

                            }
                        }
                    });
                    datePickerDialog.setCanceledOnTouchOutside(false);
                    datePickerDialog.show();


                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });


        mUserMainReceiveUserInfoPlaceOrderTimesInputInc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    int count = Integer.parseInt(mUserMainReceiveUserInfoPlaceOrderTimesInput.getText()
                            .toString());
                    count--;
                    if (count < 1) count = 1;
                    mUserMainReceiveUserInfoPlaceOrderTimesInput.setText(String.valueOf(count));
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveUserInfoPlaceOrderTimesInputAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    int count = Integer.parseInt(mUserMainReceiveUserInfoPlaceOrderTimesInput.getText()
                            .toString());
                    count++;
                    mUserMainReceiveUserInfoPlaceOrderTimesInput.setText(String.valueOf(count));
                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
        mUserMainReceiveUserInfoPlaceOrderPlaceOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    if (!Tools.Deshak()) return;

                    if (StringUtils.isEmpty(data.getString("gameType"))) {
                        AppParams.getInstance().deshakLast = 0;
                        mUserMainReceiveUserInfoPlaceOrderGametype.performClick();
                        return;
                    }
                    if (StringUtils.isEmpty(data.getString("serviceType"))) {
                        AppParams.getInstance().deshakLast = 0;
                        mUserMainReceiveUserInfoPlaceOrderServicetype.performClick();
                        return;
                    }
                    if (StringUtils.isEmpty(data.getString("startTimeHour")) || StringUtils.isEmpty(data.getString("startTimeMinute")) || StringUtils.isEmpty(data.getString("month")) || StringUtils.isEmpty(data.getString("day"))) {
                        AppParams.getInstance().deshakLast = 0;
                        mUserMainReceiveUserInfoPlaceOrderStarttime.performClick();
                        return;
                    }


                    data.put("serviceTimes", mUserMainReceiveUserInfoPlaceOrderTimesInput.getText()
                            .toString());


                    data.put("merchantId", merchantInfo.getString("merchantid"));
                    data.put("merchantPhone", merchantInfo.getString("phone"));


                    Beans beansIn = new Beans();
                    beansIn.getJsonObject()
                            .put("phone", AppParams.getInstance().appCurrentUser.getJsonObject()
                                    .getString("phone"));
                    beansIn.getJsonObject().put("data", data.toJSONString());
                    beansIn.getJsonObject().put("merchantId", merchantInfo.getString("merchantid"));
                    WaitDialog.show("请稍后...");

                    AppParams.getNewNetWork()
                            .setInterface(new NetWorkInterface() {
                                @Override
                                public int success(String msg) {
                                    try {
                                        JSONObject msgFromServer = JSON.parseObject(msg);
                                        if (Objects.equals(msgFromServer.getString("result"), "成功")) {
                                            PopTip.show("下单成功!");
                                            data.put("ordernum", msgFromServer.getString("ordernum"));

                                            bean.getJsonObject()
                                                    .put("orderData", data.toJSONString());

                                            Message message = new Message();
                                            message.what = 1;
                                            Bundle bundle = new Bundle();
                                            bundle.putString("bean", bean.getJsonObject()
                                                    .toJSONString());
                                            message.setData(bundle);
                                            UserMainReceiveOrderDetail userMainReceiveOrderDetail = (UserMainReceiveOrderDetail) AppParams.getInstance().sysfragmentmanager.findFragmentByTag("UserMainReceiveOrderDetail");
                                            if (userMainReceiveOrderDetail != null) {
                                                userMainReceiveOrderDetail.handler.sendMessage(message);
                                                userMainReceiveOrderDetail.handler.postDelayed(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        WaitDialog.dismiss();
                                                        SysManagerFragments.switchOnSysFragment("UserMainReceiveOrderDetail");

                                                    }
                                                }, 200);
                                            }


                                        }
                                    } catch (Throwable e) {
                                        ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                                    }
                                    return 0;
                                }

                                @Override
                                public int failed(String msg) {
                                    return 0;
                                }
                            })
                            .execute(AppParams.getInstance().baseUrl + "/orderCreate", beansIn.getJsonObject()
                                    .toJSONString());

                } catch (Throwable e) {
                    ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
                }
            }
        });
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initChanged();
        }
    }

    private void initChanged() {
        try {


            UIRefresh();
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }

    private void UIRefresh() {
        try {
            merchantInfo = JSON.parseObject(bean.getJsonObject().getString("merchantInfo"));
            skillsList = JSON.parseArray(bean.getJsonObject().getString("skillsList"));
            serviceType = JSON.parseObject(merchantInfo.getString("servicetype"));

            if (merchantInfo != null && !merchantInfo.isEmpty()) {
                String filename = merchantInfo.getString("phone") + "_merchant_headshot_upload.png";


                Picasso.with(MainActivity.getInstance())
                        .load(AppParams.getInstance().uploadMediaLocationServer + "/" + filename)
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .networkPolicy(NetworkPolicy.NO_CACHE)
                        .into(mUserMainReceiveUserInfoPlaceOrderHeadshot);
            }

            JSONObject data = JSON.parseObject(merchantInfo.getString("data"));
            if (data != null) {

                if (!StringUtils.isEmpty(data.getDoubleValue("merchantScore") + "")) {
                    mUserMainReceiveUserInfoPlaceOrderMerchantScore.setText(String.format("%s分", data.getDoubleValue("merchantScore")));
                }
                else {
                    mUserMainReceiveUserInfoPlaceOrderMerchantScore.setText("0.0分");
                }
                if (!StringUtils.isEmpty(data.getString("merchantName"))) {
                    mUserMainReceiveUserInfoPlaceOrderMerchantName.setText(data.getString("merchantName"));
                }
                else {
                    if (Objects.equals(data.getString("bodyType"), "企业") || Objects.equals(data.getString("bodyType"), "个体工商户")) {
                        mUserMainReceiveUserInfoPlaceOrderMerchantName.setText(data.getString("companiesMerchantAbbreviation"));
                    }
                    else if (Objects.equals(data.getString("bodyType"), "个人")) {
                        mUserMainReceiveUserInfoPlaceOrderMerchantName.setText(data.getString("individualMerchantAbbreviation"));
                    }
                }
                if (!StringUtils.isEmpty(data.getString("merchantManifesto"))) {
                    mUserMainReceiveUserInfoPlaceOrderMerchantDesc.setText(data.getString("merchantManifesto"));
                }
            }
        } catch (Throwable e) {
            ExceptionUtils.getException(ExceptionUtils.getTraceInfo(), e);
        }
    }
}